import { observer } from "mobx-react-lite"
import React from "react"
import { View, ViewStyle, FlatList, Text, StyleSheet, useWindowDimensions } from "react-native"
import { colors, spacing } from "../../theme"
import { useSafeAreaInsetsStyle } from "../../utils/useSafeAreaInsetsStyle"
import NotificationItem from "./NotificationItem"
import MainHeader from "app/components/MainHeader"
import { useAppDispatch, useAppSelector } from "app/redux/hooks"
import { getNotifications, updateNotifcation } from "app/redux/actions/notificationAction"
import { resetNotification, setNotificationLoader } from "app/redux/slices/notificationSlice"
import { useFocusEffect } from "@react-navigation/native"
import LoaderComponent from "app/components/Loader"
import { scale } from "react-native-size-matters"

const ItemSeparatorComponent = () => {
  return <View style={{ height: 15 }} />
}

export const Notifications = observer(function WelcomeScreen() {
  const $bottomContainerInsets = useSafeAreaInsetsStyle(["bottom", "top"])
  const dispatch = useAppDispatch()
  const notifcationSelector = useAppSelector((state) => state?.notification)

  const { height } = useWindowDimensions()

  const updateNotifcations = (id) => {
    dispatch(setNotificationLoader({ id }))
    dispatch(updateNotifcation({ id }))
  }

  useFocusEffect(
    React.useCallback(() => {
      dispatch(getNotifications())
      return () => {
        dispatch(resetNotification())
      }
    }, []),
  )

  return (
    <View style={[$container, $bottomContainerInsets]}>
      <MainHeader />
      {notifcationSelector?.loading === true ? (
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <LoaderComponent />
        </View>
      ) : (
        <FlatList
          data={notifcationSelector?.notification}
          extraData={notifcationSelector?.notification}
          keyExtractor={(item, index) => index.toString()}
          // @ts-ignore TODO
          renderItem={({ item }) => <NotificationItem item={item} onPress={updateNotifcations} />}
          ItemSeparatorComponent={ItemSeparatorComponent}
          ListEmptyComponent={
            <View style={[styles.emptyComponent, { height: height * 0.7 }]}>
              <Text style={styles.listText}>No records found</Text>
            </View>
          }
          contentContainerStyle={{
            paddingHorizontal: spacing.lg,
            paddingVertical: spacing.lg,
            paddingBottom: 130,
          }}
        />
      )}
    </View>
  )
})

const $container: ViewStyle = {
  flex: 1,
  backgroundColor: colors.background,
}
const styles = StyleSheet.create({
  listText: {
    color: colors.black,
    fontSize: scale(18),
    fontWeight: "600",
  },
  emptyComponent: {
    alignItems: "center",
    justifyContent: "center",
    flex: 1,
  },
})
